package com.denghq.projectbuilder.component.basedatacache.builder;

import com.denghq.projectbuilder.component.basedatacache.autoconfigure.BaseDataCacheProperties;
import com.denghq.projectbuilder.component.basedatacache.autoconfigure.ICommonCacheDomain;
import com.denghq.projectbuilder.component.basedatacache.autoconfigure.ICustomCacheDomain;
import com.denghq.projectbuilder.component.basedatacache.cache.ICacheDomain;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 缓存对象容器
 */
public class SimpleCacheDomainListContainer implements ICacheDomainListContainer {

    private final BaseDataCacheProperties properties;

    private final List<ICacheDomain> cacheDomainList;

    public SimpleCacheDomainListContainer(BaseDataCacheProperties properties, List<ICustomCacheDomain> customCacheDomainList, List<ICommonCacheDomain> commonCacheDomainList) {
        this.properties = properties;
        this.cacheDomainList = buildCacheDomains(customCacheDomainList, commonCacheDomainList);
    }

    @Override
    public List<ICacheDomain> getCacheDomainList() {
        return this.cacheDomainList;
    }

    private List<ICacheDomain> buildCacheDomains(List<ICustomCacheDomain> customCacheDomainList, List<ICommonCacheDomain> commonCacheDomainList) {
        List<ICacheDomain> list = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(customCacheDomainList)) {
            list.addAll(customCacheDomainList);
        }
        if (CollectionUtils.isEmpty(properties.getUseCache())) {
            //list.addAll(commonCacheDomainList);
            return list;
        } else {
            properties.getUseCache().forEach(cacheType -> {
                        for (int i = 0, len = commonCacheDomainList.size(); i < len; i++) {
                            if (commonCacheDomainList.get(i).getCacheKey().equals(cacheType)) {
                                list.add(commonCacheDomainList.get(i));
                                break;
                            }
                        }
                    }
            );
        }
        return list;
    }
}
